<template>
  <view :class="theme">
    <view class="fixed"
      style="top: 0; left: 0; right: 0; bottom: auto; top: var(--window-top); left: var(--window-left); right: var(--window-right);">
      <u-image width="100%" height="610" src="/static/img/bg-auth.png" />
    </view>

    <view style="z-index: 9;">
      <view class="ai-center" style="margin: 220rpx auto 0;">
        <u-image radius="16" width="120" height="120" src="/static/logo.png" />
        <text class="mt-12 fs-32 fw-700">{{ systemInfo.appName }}</text>
      </view>
      <view class="oh bg-2" style="margin: 60rpx 40rpx; border-radius: 60rpx 60rpx 36rpx 36rpx;">
        <view class="fd-row">
          <view @click="changeCurrentTab(index)" v-for="(tab, index) in tabs.list" :key="index"
            class="relative f1 jc-center ai-center height-100"
            :style="{ backgroundColor: index === tabs.current ? `#fff` : `#fff2fc`, borderRadius: tab.radius }">
            <text :class="index === tabs.current ? 'color-3 fs-36' : `color-4 fs-30`"
              style="transition: all ease-in-out 0.1s;">{{ tab.name }}</text>
            <view :style="{ width: index === tabs.current ? `44rpx` : 0, transition: `all ease-in-out 0.1s` }"
              class="absolute bottom-0 height-8 br-4 bg-5" />
          </view>
        </view>

        <view class="p-30">
          <view class="br-12 fd-row ai-center pl-28 pr-28"
            style="margin: 60rpx 30rpx 30rpx; background-color: #f6faff; height: 88rpx;">
            <u-icon size="32" color="#999" name="phone" />
            <input v-model="formData.phoneNumber.value" class="f1 ml-24 height-100percent fs-28" type="number"
              maxlength="11" placeholder="请输入手机号码" placeholder-class="color-9" />
          </view>

          <view v-if="tabs.current" class="br-12 fd-row ai-center pl-28 pr-28"
            style="background-color: #f6faff; height: 88rpx; margin: 0 30rpx;">
            <u-icon size="32" color="#999" name="lock" />
            <input v-model="formData.captcha.value" class="f1 ml-24 height-100percent fs-28" type="number" maxlength="6"
              placeholder="请输入验证码" placeholder-class="color-9" />
            <button @click="getCaptcha" :disabled="formData.captcha.disabled" hover-class="tap-hover" plain
              hover-start-time="50" class="border-none m-6 ai-center jc-center color-5 fs-24 br-52"
              style="width: 160rpx;">
              {{ formData.captcha.text }}
            </button>
          </view>

          <view v-else class="br-12 fd-row ai-center pl-28 pr-28"
            style="background-color: #f6faff; height: 88rpx; margin: 0 30rpx;">
            <u-icon size="32" color="#999" name="lock" />
            <input v-model="formData.password.value" class="f1 ml-24 height-100percent fs-28" type="password"
              maxlength="16" placeholder="请输入密码" placeholder-class="color-9" />
          </view>

          <button @click="login" hover-class="tap-hover" class="bg-6 color-2 br-20"
            style="margin: 60rpx 30rpx 30rpx;">登录</button>
          <view class="fd-row jc-sb color-6" style="margin: 0 30rpx 30rpx;">
            <navigator class="pt-30 pb-30" hover-class="tap-hover" url="/pages/client/auth/register">
              去注册
            </navigator>
            <navigator class="pt-30 pb-30" hover-class="tap-hover" url="/pages/client/auth/reset">
              忘记密码?
            </navigator>
          </view>

          <label class="m-30 jc-center">
            <switch :checked="formData.isAgree.value" @change="(e: any) => formData.isAgree.value = e.detail.value"
              type="checkbox" color="#fff" />
            <view class="fd-row color-9">
              <text>我已阅读并同意</text>
              <navigator @click.stop.prevent :url="buildDocumentURL('服务协议', '/userAgreementInfo')" hover-class="tap-hover"
                style="text-decoration: underline;">
                《服务条款》
              </navigator>
              <text>和</text>
              <navigator @click.stop.prevent :url="buildDocumentURL('隐私政策', '/privateInfo')" hover-class="tap-hover"
                style="text-decoration: underline;">
                《隐私政策》
              </navigator>
            </view>
          </label>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { checkVersion } from "@/common/libs/dependency";
import { useMapState } from "@/common/libs/store";
import { getClient, pickObjectProperty, transformURL } from "@/common/libs/utils";
import { onLoad } from "@dcloudio/uni-app";
import { reactive } from "vue";

const { $config = {} } = getApp().globalData || {};
const { theme } = useMapState(["theme"]);
const systemInfo = uni.getSystemInfoSync();
const buildDocumentURL = (title: string, api: string) => transformURL("/pages/common/webview",
  {
    title: encodeURIComponent(title),
    url: encodeURIComponent(transformURL("/document.html",
      { title },
      $config.URL_REMOTE + $config.API_PREFIX + api
    ))
  }
);
const tabs = reactive({
  list: [
    { name: "密码登录", radius: `60rpx 0` },
    { name: "验证码登录", radius: `0 60rpx` },
  ],
  current: 0
});

const formData = reactive({
  phoneNumber: {
    value: "",
    errorMessage: "手机号码输入有误",
    field: "mobile",
    rule: /^1[0-9]{10}$/
  },
  password: {
    value: "",
    errorMessage: "请输入密码",
    field: "password",
    isVisible: false,
    rule: /^.+$/
  },
  captcha: {
    text: "验证码",
    errorMessage: "验证码输入有误",
    disabled: false,
    count: 60,
    timer: null as any,
    value: "",
    field: "code",
    rule: /^[0-9]{4,8}$/
  },
  isAgree: {
    value: true,
    errorMessage: "请先阅读并同意服务条款和隐私政策。",
    rule: /^true$/,
  }
});

onLoad(() => {
  [5, 6].includes(getClient()) && checkVersion();
});

// let wv: any;
const getCaptcha = () => {
  // if (wv) {
  //   return wv.show();
  // }
  // wv = plus.webview.create('', 'custom-webview', {
  //   'uni-app': 'none',
  //   background: 'transparent',
  //   webviewBGTransparent: true,
  //   height: "100%",
  //   width: "100%",
  //   top: "0"
  // } as any, {
  //   appkey: "FFFF0N0000000000B4D6",
  //   scene: "nc_login_h5"
  // })
  // wv.loadURL('/static/server/verify.html');
  // const pages = getCurrentPages();
  // const currentPages: any = pages[pages.length - 1];
  // var currentWebview = currentPages.$getAppWebview();
  // currentWebview.append(wv);

  // (plus as any).globalEvent.addEventListener('plusMessage', (msg: any) => {
  //   const result = msg.data.args.data
  //   if (result.name == 'postMessage') {
  //     console.log(result);
  //   }
  // })
  // return;
  const { captcha, phoneNumber } = formData;
  if (captcha.disabled) return;
  uni.showToast({ icon: "loading", mask: true });
  if (!phoneNumber.rule.test(phoneNumber.value)) {
    uni.showToast({
      title: phoneNumber.errorMessage,
      icon: "none",
      mask: true
    });
    return;
  }
  uni.request({
    url: "/sendSms",
    data: {
      mobile: formData.phoneNumber.value,
      type: "fastLogin",
    },
    success: ({ msg: title }: any) => {
      uni.showToast({ title, icon: "none" })
    }
  });
  countDown();
}

const countDown = () => {
  const { captcha } = formData;
  captcha.disabled = true;

  const intervalTask = () => {
    captcha.count--;
    captcha.text = `${captcha.count}S`;

    if (captcha.count <= 0) {
      captcha.disabled = false;
      captcha.text = "重新获取";
      captcha.count = 60;
      captcha.timer && clearInterval(captcha.timer);
      captcha.timer = null;
    }
    return intervalTask;
  }
  captcha.timer = setInterval(intervalTask(), 1000);
}

const login = () => {
  const params = pickObjectProperty(["isAgree", "phoneNumber", tabs.current ? "captcha" : "password"], formData);

  const data: any = {},
    verification = (<Array<keyof typeof params>>Object.keys(params)).every(key => {
      const { value, field, errorMessage: title, rule } = params[key] as any;

      if (title && !rule.test(String(value))) {
        uni.showToast({ title, icon: "none" });
        return false;
      }

      field && (data[field] = value);
      return true;
    });

  if (!verification) return;
  uni.showToast({ icon: "loading", mask: true });
  uni.request({
    url: ["/login", "/fastUcLogin1"][tabs.current], data,
    async success({ data }: any) {
      uni.hideToast();
      await uni.setStorage({
        key: $config.STORAGE_KEY_USER_INFO,
        data: { value: data, expireTime: $config.STORAGE_USER_INFO_EXPIRE_TIME },
      });
      uni.reLaunch({ url: $config.PAGE_HOME_CLIENT });
    }
  });
}

const changeCurrentTab = (index: number) => {
  if (tabs.current === index) return;
  tabs.current = index;
}


</script>

<style lang="scss" scoped>
// scss
::v-deep {
  switch {
    transform: scale(0.7);

    .wx-checkbox-input,
    .uni-checkbox-input {
      &:empty {
        border-color: $uni-bg-color-grey;
        background-color: transparent;
      }

      &:not(:empty) {
        border-color: transparent;
        background-color: $uni-bg-color-primary;
      }

      border-width: 2px;
      border-radius: 50%;
    }

    .wx-checkbox-input.wx-checkbox-input-checked,
    .uni-checkbox-input.uni-checkbox-input-checked {
      border-color: $uni-bg-color-grey;
      background-color: $uni-bg-color-primary;
    }

    &:not([disabled]) {

      .wx-checkbox-input:hover,
      .uni-checkbox-input:hover {
        border-color: $uni-bg-color-grey;
      }
    }
  }
}
</style>